<template>
	<a-modal
		title="导入"
		@cancel="onClose"
		@onOk="onClose"
		:width="700"
		:footer="null"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<span
			>导入数据格式严格按照系统模板进行数据录入，请点击
			<a-button type="primary" size="small" @click="emit('downloadTemplate')">下载模板</a-button>
		</span>
		<a-divider dashed />
		<div>
			<a-spin :spinning="impUploadLoading">
				<a-upload-dragger :show-upload-list="false" :custom-request="customRequestLocal" :accept="uploadAccept">
					<p class="ant-upload-drag-icon">
						<inbox-outlined></inbox-outlined>
					</p>
					<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
					<p class="ant-upload-hint">仅支持xls、xlsx格式文件</p>
				</a-upload-dragger>
			</a-spin>
		</div>
	</a-modal>
</template>

<script setup name="userImpExp">
	import { message } from 'ant-design-vue'

	const impUploadLoading = ref(false)
	const impAccept = [
		{
			extension: '.xls',
			mimeType: 'application/vnd.ms-excel'
		},
		{
			extension: '.xlsx',
			mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		}
	]
	// 指定能选择的文件类型
	const uploadAccept = String(
		impAccept.map((item) => {
			return item.mimeType
		})
	)

	const props = defineProps({
		uploadRequest: {
			type: Promise,
			default: undefined,
			required: true
		}
	})
	// 导入
	const customRequestLocal = (data) => {
		impUploadLoading.value = true
		const fileData = new FormData()
		// 校验上传文件扩展名和文件类型是否为.xls、.xlsx
		const extension = '.'.concat(data.file.name.split('.').slice(-1).toString().toLowerCase())
		const mimeType = data.file.type
		// 提取允许的扩展名
		const extensionArr = impAccept.map((item) => item.extension)
		// 提取允许的MIMEType
		const mimeTypeArr = impAccept.map((item) => item.mimeType)
		if (!extensionArr.includes(extension) || !mimeTypeArr.includes(mimeType)) {
			message.warning('上传文件类型仅支持xls、xlsx格式文件！')
			impUploadLoading.value = false
			return false
		}
		fileData.append('file', data.file)
		return props
			.uploadRequest(fileData)
			.then(() => {
				onClose()
			})
			.finally(() => {
				impUploadLoading.value = false
			})
	}

	// 定义emit事件
	const emit = defineEmits({ downloadTemplate: null })
	// 默认是关闭状态
	const visible = ref(false)

	// 打开抽屉
	const onOpen = () => {
		visible.value = true
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
